function [ output subjectinfo ] = plotClusteredTfcPeaks( clusterdata, cfg )
%PLOTCLUSTEREDTFCPEAKS

if ~exist('cfg', 'var') || isempty(cfg)
    cfg = plotClusteredTfcPeaks_defaultCfg;
end

% Create a subselection of bins to do based on config...
% bins = unique({clusterdata.bin});
bins= {'4-7Hz','7-13Hz', '13-30Hz', '30-70Hz', '70-130Hz'}; 
if ~isempty(cfg.FrequencyBinSelection)
    binTf = false(size(bins));
    for i = 1:length(cfg.FrequencyBinSelection); binTf = binTf | strcmp(cfg.FrequencyBinSelection{i}, bins); end;
    bins = bins(binTf);
end

% Create a subselection of epochs to do based on config...
epochsets = unique({clusterdata.epochset});
if ~isempty(cfg.EpochSetSelection)
    epTf = false(size(epochsets));
    for i = 1:length(cfg.EpochSetSelection); epTf = epTf | strcmp(cfg.EpochSetSelection{i}, epochsets); end;
    epochsets = epochsets(epTf);
end

subjects = unique({clusterdata.subject});


%% Get all the clusters to be displayed in one plot

for s = subjects
  for e = epochsets
        eTf = strcmp(cell2mat(e), {clusterdata.epochset}) & strcmp(cell2mat(s), {clusterdata.subject});
        eClusters = clusterdata(eTf);
        if isempty(eClusters); continue; end;
      
      f = figure; hold on;
           for b = 1:length(bins)
                    %% Create the set of subplots as needed
                    qTf = strcmp(bins(b), {clusterdata.bin}) & strcmp(cell2mat(e), {clusterdata.epochset}) & strcmp(cell2mat(s), {clusterdata.subject});
                    qClusters = clusterdata(qTf);

                    subplot(2,ceil(length(bins)/2),b); hold on;
                    ylabel(bins(b));
                    set(gca, ...
                    'YGrid','on',...
                    'XGrid','on',...
                    'XLim', [-4000,4000]);
            %         'XTick',[0 125 250 375 500 625 750 875 1000],...
            %         'XTickLabel',{'-4s','','-2s','','=O=','','2s','','4s'});
            % %         'XTickLabel',{'','','','','','','','',''});
                if b==2
%                     if cfg.DrawRegression
%                       title([cell2mat(s) ' / ' cell2mat(e) ' - Regression coefficient']);
%                     else
%                       title([cell2mat(s) ' / ' cell2mat(e) ' - Mean of cluster']);
%                     end;

                   if cfg.DrawStddevs 
                        errtitle = 'on';
                   else errtitle = 'off';
                   end;
                   
                     if cfg.DrawRegression
                        if cfg.SubplotByRegion == 0;
                          title(['Regression of Tfc clusters - ' cell2mat(s) ' - ' cell2mat(e),10, 'All regions - Errorbars ' errtitle ]); 
                         else
                          title(['Regression of Tfc clusters - ' cell2mat(s) ' - ' cell2mat(e),10,  'Selection of Regions - Errorbars ' errtitle ]); 
                        end;
                     else 
                        if cfg.SubplotByRegion == 0;
                          title(['Average of Tfc clusters - ' cell2mat(s) ' - ' cell2mat(e),10,  'All regions - Errorbars ' errtitle ]); 
                        else
                          title(['Average of Tfc clusters - ' cell2mat(s) ' - ' cell2mat(e),10,  'Selection of Regions - Errorbars ' errtitle ]); 
                        end;
                     end

                end

                    %         sp{1}.aHandle = subplot(2,1,1);
                    %         sp{2}.aHandle = subplot(2,1,2);


                    %% Sections the data by visual representation

                    if cfg.SubplotByRegion == 0;
                            regions = unique({qClusters.region}); end;
                    if cfg.SubplotByRegion == 1;
                            regions = cfg.SubplotSelection1; end;
                    if cfg.SubplotByRegion == 2;
                            regions = cfg.SubplotSelection2; end;

                    for r = regions
                        clusters = qClusters(strcmp(cell2mat(r), {qClusters.region}));
                        if isempty(clusters);  
                                       continue; end;

                        % Decide what subplot to use..
                        %             for i=1:length(cfg.SubplotByRegion);
                        %                 if any(strcmp(cell2mat(r), cfg.SubplotByRegion(i).Selection))
                        %                     subplot(2,1,i);
                        %                     break;
                        %                 end
                        %             end

                        % Draw the regression arrows
                        %           if cfg.DrawRegression

                        %               Tb = clusters.meanTime;
                        %               Vb = clusters.meanValue;
                        %               Te = ones(size(Tb)) * 1000;
                        %               Ve = ones(size(Vb)) * 0.1;
                        %               quiver(Tb, Vb, Te, Ve);

            %             for i = 1:length(clusters)
            %                 if length(clusters(i).members)>1 && ~isnan(clusters(i).regression2.polyfit)
            %                     Tb = clusters(i).meanTime/1000;
            %                     Vb = clusters(i).meanValue;
            %                     
            %                     s = 0.05; %(length of arrow..)
            %                     alpha = atan(clusters(i).regression2.polyfit);
            %                     deltaV = cos(alpha) * s;
            %                     deltaT = sin(alpha) * s;
            %                     Te = Tb + deltaT;
            %                     Ve = Vb + deltaV;
            %                     
            %                     warning('off');
            %                     arrow([Tb*1000,Vb], [Te*1000,Ve], 3, 30);
            %                     warning('on');
            %                 end
            %             end

                        % Get the correct marker
                        mCfgMs = fieldnames(cfg.Markers);
                        markerIdx=[];
                        for i = 1:length(mCfgMs)
                            if cfg.Markers.(mCfgMs{i}).Description == cell2mat(r)
                                markerIdx = mCfgMs{i};
                                break;
                            end
                            if isempty(markerIdx); markerIdx = 'Other'; end;
                        end
                        mrk = cfg.Markers.(markerIdx);
                        % Make sure the face is plotted as white in case it is undefined.
                        if isempty(mrk.MarkerFaceColor); mrk.MarkerFaceColor = [1 1 1]; end;

                        Tm = [clusters.meanTime];
                        Vm = [clusters.meanValue];
                        Ts = [clusters.stdTime];
                        Vs = [clusters.stdValue];

                        Rcoeff = ones(length(clusters),1);
                        RconfU = ones(length(clusters),1);            
                        RconfL = ones(length(clusters),1);

                        for p=1:length(clusters);
                        Rcoeff(p) = clusters(p).regression.coeff;
                        RconfU(p) = clusters(p).regression.confidence(1);
                        RconfL(p) = clusters(p).regression.confidence(2);
                        end

                      %plot regression coefficient
                      if cfg.DrawRegression
                          if cfg.DrawStddevs
                              hRH = herrorbar(Tm,Rcoeff,Ts,'.');
                            % Turn off legend annotation
                            hRAnnotation = get(hRH,'Annotation');
                            for a = 1:length(hRAnnotation)
                                hRLegendEntry = get(hRAnnotation{a},'LegendInformation');
                                set(hRLegendEntry,'IconDisplayStyle','off')
                            end
                            hRE = errorbar(Tm,Rcoeff,RconfL,RconfU,...
                                'LineStyle','none',...
                                'Marker', mrk.Marker, ...
                                'MarkerSize', 6, ...
                                'MarkerEdgeColor', mrk.MarkerEdgeColor, ...
                                'MarkerFaceColor', mrk.MarkerFaceColor);
                            set(hRE, 'DisplayName', cell2mat(r));
                          else
                            hRS = scatter(Tm, Rcoeff,...
                             'Marker', mrk.Marker, ...
                             'MarkerEdgeColor', mrk.MarkerEdgeColor, ...
                             'MarkerFaceColor', mrk.MarkerFaceColor);
                              set(hRS, 'DisplayName', cell2mat(r)); 
                          end
                      else % scatterplot mean of cluster
                         if cfg.DrawStddevs
                            hH = herrorbar(Tm,Vm,Ts,'.');
                            % Turn off legend annotation
                            hAnnotation = get(hH,'Annotation');
                            for a = 1:length(hAnnotation)
                                hLegendEntry = get(hAnnotation{a},'LegendInformation');
                                set(hLegendEntry,'IconDisplayStyle','off')
                            end;
                            hE = errorbar(Tm,Vm,Vs,...
                                'LineStyle','none',...
                                'Marker', mrk.Marker, ...
                                'MarkerSize', 6, ...
                                'MarkerEdgeColor', mrk.MarkerEdgeColor, ...
                                'MarkerFaceColor', mrk.MarkerFaceColor);
                            set(hE, 'DisplayName', cell2mat(r));
                         else
                            hS = scatter(Tm, Vm, ...
                                'Marker', mrk.Marker, ...
                                'MarkerEdgeColor', mrk.MarkerEdgeColor, ...
                                'MarkerFaceColor', mrk.MarkerFaceColor);
                            set(hS, 'DisplayName', cell2mat(r));
                         end
                      end


                        % 3D plotje testen..
                        %             ZZ = [clusters.regression2];
                        %             Z = atand([ZZ.polyfit]);
                        %             scatter3(Tm, Vm, Z, ...
                        %                     'Marker', mrk.Marker, ...
                        %                     'MarkerEdgeColor', mrk.MarkerEdgeColor, ...
                        %                     'MarkerFaceColor', mrk.MarkerFaceColor);
                        % Draw the subject names and the legend..
                        %             error('TODO');
                    end
                
          end
         
        subplot(2,ceil(length(bins)/2),1);
%         legend1 = legend(regions);
        legend1 = legend('show');
        set(legend1,'Position',[0.7 0.25 0.06 0.15]);
        
            if cfg.SubplotByRegion == 0;
                seltitle = 'All Regions'; end;
            if cfg.SubplotByRegion == 1;
                seltitle = 'SelectionOfRegions 1'; end;
            if cfg.SubplotByRegion == 2;
                seltitle = 'SelectionOfRegions 2'; end;
        
       if cfg.SaveFigure
         if cfg.DrawRegression
              saveFigure(f, [getpref('ECoG','Results') 'Clustered\'], cell2mat({'RegressionTfcClusters - ' cell2mat(s) ' ' cell2mat(e) ' - ' seltitle ' Errorbars ' errtitle })); 
              close(f);
         else 
              saveFigure(f, [getpref('ECoG','Results') 'Clustered\'], cell2mat({'AverageTfcClusters - ' cell2mat(s) ' ' cell2mat(e) ' - ' seltitle ' Errorbars ' errtitle })); 
              close(f);
         end
       end

   end



end
end